package zhr.chapter12;

public class BreadContainer {
    public static final int maxNum = 300;
    private int num;

    public BreadContainer() {
    }

    public BreadContainer(int num) {
        this.num = num;
    }

    public synchronized void produceBread(int produceNum, String producerName) {
        while (num + produceNum < maxNum) {
            System.out.println(producerName + "要生产" + produceNum + "个面包,当前" + num + "个面包,资源充足,不需要生产," + producerName + "去等待!");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num =num+produceNum;
        System.out.println(producerName + "生产了" + produceNum + "个面包,当前有" + num + "个面包");
        notifyAll();
    }

    public synchronized void consumeBread(int consumeNum, String consumerName) {
        while (consumeNum > num) {
            System.out.println(consumerName + "要消费" + consumeNum + "个面包,由于现在只有" + num + "个," + consumerName + "于是去等待!");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        num =num- consumeNum;
        System.out.println(consumerName + "消费了" + consumeNum + "个面包,现在还剩下" + num + "个面包");
        notifyAll();
    }

}